<?php

namespace Modules\Market\Entities;

use Modules\Core\Entities\BaseEntity as Model;
use ThrowException;

use DB;
// use Modules\Core\Traits\Likeable;
use Modules\Asset\Entities\PackageSku;

class ExchangeRecord extends Model
{
	// use Likeable;

    protected $guarded = [];
    protected $table = 'exchange_records';
    protected $appends = ['union_status', 'union_status_text'];

    static public $resourceName = '置换记录';

    public $packageSkus = [];
    public $productSku = NULL;

    protected $casts = [
    ];

    public function user()
    {
    	return $this->belongsTo('\Modules\User\Entities\User', 'user_id');
    }

    public function package_skus()
    {
        return $this->hasMany('\Modules\Asset\Entities\PackageSku', 'exchange_record_id');
    }

    public function product_sku()
    {
        return $this->belongsTo('\Modules\Product\Entities\Sku', 'sku_id');
    }

    // 统一状态
    public function getUnionStatusAttribute()
    {
        $status = 'unknow';

        $map = [
            1 => 'pending',
            2 => 'completed',
            3 => 'closed',
        ];

        return $map[$this->status];
    }

    // 统一状态
    public function getUnionStatusTextAttribute()
    {
         $map = [
            'pending' => '待支付',
            'completed' => '已完成',
            'closed' => '已关闭',
        ];

        return $map[$this->union_status];
    }

    // 状态筛选
    public function scopeStatus($query, $status)
    {
        if ($status === 'all') {
            return $query;
        };
        
        $statusMap = [
            'pending' => 1,
            'completed' => 2,
            'closed' => 3,
        ];
        return $query->where('status', $statusMap[$status]);
    }

    // 用仓库sku和商品sku初始化一个置换记录
    static public function initWith($user, $packageSkus, $productSku)
    {
        if ($packageSkus->count() === 0) {
            ThrowException::Conflict('没有可兑换的物品~');
        }

        foreach ($packageSkus as $packageSku) {
            if ($packageSku->union_status != 'pending') {
                ThrowException::Conflict('部分物品不在可兑换状态~');
            }
        }

        list($moneyPrice, $scorePrice) = PackageSku::calcExchangeInfoForList($packageSkus);

        $info = [
            'uuid' => uniqid(),
            'user_id' => $user->id,
            'product_id' => $productSku->product_id,
            'sku_id' => $productSku->id,
            'source_money_price' => $moneyPrice,
            'source_score_price' => $scorePrice,
            'target_money_price' => $productSku->money_price ?: 0,
            'target_score_price' => $productSku->score_price ?: 0,
        ];
        
        $item = new ExchangeRecord($info);

        $item->packageSkus = $packageSkus;
        $item->productSku = $productSku;

        return $item;
    }

    // 关闭
    public function close()
    {
        foreach ($this->package_skus as $sku) {
            $sku->update([
                'status' => 1
            ]);
        }

        $this->update([
            'status' => 3
        ]);
    }

    // 标记为已完成
    public function complete()
    {
        $this->update([
            'status' => 2
        ]);
    }

    // 保存所有数据
    public function createAll($order)
    {
        DB::beginTransaction();

        $this->order_number = $order->number;
        $this->pay_money_price = $order->pay_money_price;
        $this->pay_score_price = $order->pay_score_price;

        $this->save();

        foreach ($this->packageSkus as $packageSku) {
            $packageSku->update([
                'exchange_record_id' => $this->id,
                'status' => 6
            ]);
        }

        DB::commit();
    }

    static public function beforeGetList($options)
    {
        if (@$options['status']) {
            $options['scopes']['status'] = $options['status'];
        }

        return $options;
    }
}
